#include "World.h"
#include <iostream>
#include <fstream>

using namespace std;

typedef vector<Chunk_t>::iterator chIter;
typedef vector<Block_t>::iterator bIter;

World::World(std::string name) : name(name)
{
}

World::~World()
{
}
		
void World::addChunk(const Chunk_t &c)
{
	chunks.push_back(c);
}

void World::addBlock(int x, int z, const Block_t &b)
{
	chIter it;
	bIter bit;
	bool find = false;
	for(it = chunks.begin(); it != chunks.end() && !find; ++it)
	{
		if(it->x == x && it->z == z)
		{
			for(bit = it->blocks.begin(); bit != it->blocks.end() && !find; ++bit)
			{
				if(bit->x == b.x && bit->y == b.y && bit->z == b.z)
				{
					(*bit) = b;
					find = true;
				}
			}
			if(!find)
				it->blocks.push_back(b);
		}
	}
}

Block_t &World::getChunk(int x, int z)
{
}
		
void World::saveAll()
{
	ofstream file("world.txt", ios::out | ios::trunc);
    if(file)
    {
		file << chunks.size() << endl;
		chIter it;
		for(it = chunks.begin(); it != chunks.end(); ++it)
		{
			file << it->blocks.size() << endl;
			file << it->x << " " << it->z << endl;
			bIter bit;
			for(bit = it->blocks.begin(); bit != it->blocks.end(); ++bit)
			{
				Block_t b = (*bit);
				file << b.x << " " << b.y << " " << b.z << " " << b.id << endl;
			}
		}
        file.close();
    }
    else
        cerr << "Impossible d'ouvrir le file !" << endl;
}

void World::clean()
{
	chIter it;
	for(it = chunks.begin(); it != chunks.end(); ++it)
		it->blocks.clear();
	chunks.clear();
}
